# coding=utf-8
# 1.先设置编码，utf-8可支持中英文，如上，一般放在第一行

# 2.注释：包括记录创建时间，创建人，项目名称。
'''
Created on 2019-4-29
@author: 北京-宏哥
Project:学习和使用discover批量执行测试用例
'''
# 3.导入unittest模块
import datetime
import os
import time
import unittest

# 4.编写测试用例和断言
from shutil import copyfile

from common import HTMLTestRunner2
from common.Dingding import sendDingDing
from common.Sheet_data_handler import data
from common.send_email import send_email


def all_case():
    # 1、 指定测试用例和测试报告的路径
    test_case_dir = os.path.join(os.getcwd(), 'Cases')
    test_reports_dir = './reports/'
    # 2、加载测试用例
    start_time = datetime.datetime.now()
    discover = unittest.defaultTestLoader.discover(test_case_dir, pattern="test*.py", top_level_dir=None)
    # discover = unittest.defaultTestLoader.discover(test_case_dir, pattern="test_Batch_Execution_Cases.py", top_level_dir=None)  # 执行指定用例
    testcase = unittest.TestSuite()
    testcase.addTests(discover)  # 直接加载 discover

    # 3、定义测试报告文件格式
    Ding_file_prefix = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    file_prefix = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime())
    reprot_title = '%s TMS接口测试报告.html' % file_prefix

    # 4、创建并运行测试报告文件
    fp = open(test_reports_dir + '{0}'.format(reprot_title), 'wb')
    result = HTMLTestRunner2.HTMLTestRunner(stream=fp, title="测试报告").run(discover)
    end_time = datetime.datetime.now()
    time.sleep(3)

    # 5、钉钉报告文件整理
    total_count = int(result.success_count + result.error_count + result.failure_count)
    success_count = int(result.success_count)
    failure_count = int(result.failure_count)
    error_count = int(result.error_count)
    seconds = (end_time - start_time).seconds
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    total_time = "%02d分%02d秒" % (m, s)
    # total_time = (end_time - start_time).seconds
    pass_persent = '%.2f%%' % ((success_count / total_count) * 100)
    skip_count =len(data[1])
    msg = " 『TMS接口自动化测试报告』\n" \
          "时     间:  %s\n" \
          "可执行总数:  %s 个\n" \
          "成功用例数:  %s 个\n" \
          "跳过用例数:  %s 个\n" \
          "失败用例数:  %s 个\n" \
          "错误用例数:  %s 个\n" \
          "测试通过率:  %s\n" \
          "用例执行总耗时：%s \n" \
          "具体详情请及时查看邮件" % (
              Ding_file_prefix, total_count, success_count, skip_count,failure_count, error_count, pass_persent, total_time)
    print(msg)

    # 6、关闭文件
    fp.close()

    # 复制一份最新的文件作为jenkins查看
    Ori_Path = "./reports/{}".format(reprot_title)
    Tar_Path = os.getcwd() + "/reports/jenkins_report/jenkins_report.html"
    copyfile(Ori_Path, Tar_Path)

    return [result, reprot_title, file_prefix, msg]


if __name__ == "__main__":
    result = all_case()
    msg = result[3]
    reprot_title = result[1]
    print(reprot_title)
    # send_email(msg, reprot_title)  # 发送测试报告  暂时不发
    # sendDingDing(msg)  # 发送钉丁
